<template>
  <el-container style="height: 100%; display: flex; flex-direction: column;">
    <el-header style="display: flex; justify-content: space-between; align-items: center;">
      <el-dropdown @command="handleFilter">
        <el-button type="primary" style="width:10vw;">
          {{ Filter }}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item v-for="(item, index) in tableTitle" :command="item.label">{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>

      <el-input v-model="search" placeholder="请输入内容" clearable="true" style="width: 20vw;"></el-input>
      <el-button @click="handleSearch" :disabled="search ? false : true">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="handleRefresh">刷新</el-button>

      <!--新建下拉框-->
      <el-dropdown @command="handleAdd">
        <el-button type="primary">
          编辑<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="addAdmin">管理员新增</el-dropdown-item>
          <el-dropdown-item command="addRules">策略新增</el-dropdown-item>
          <el-dropdown-item command="viewRules">策略查看</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>



    </el-header>
    <el-main style="flex: 1; overflow-y: auto;">
      <el-table :data="paginatedData" style="width:100%" v-loading="loading">
        <el-table-column v-for="(item, index) in tableTitle" align="center" :key="index" :prop="item.tableProp" :label="item.label" :formatter="formatFlag" :width="item.width"></el-table-column>

        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="handleDetails(scope.row)" type="text" size="small">详情</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>


    <!--管理员添加或者详情对话框-->
    <el-dialog v-bind:title="dialogTitle" :visible.sync="dialogAdminFormVisible">
      <el-form ref="Adminform" :rules="rules" :model="Adminform" @submit.native.prevent>
        <el-form-item prop="name" label="管理员姓名" :label-width="formLabelWidth">
          <el-input v-model="Adminform.name" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>
        <!--新增页面才显示密码，编辑不能修改密码-->
        <el-form-item v-if="!isall" prop="password" label="管理员密码" :label-width="formLabelWidth">
          <el-input v-model="Adminform.password" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>

        <el-form-item v-if="isall" prop="newpassword" label="输入新密码" :label-width="formLabelWidth">
          <el-input v-model="Adminform.newpassword" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>

        <!--策略下拉框-->
        <el-form-item prop="roleId" label="策略" :label-width="formLabelWidth">
          <el-select v-model="Adminform.roleId" placeholder="请选择策略" :disabled="!isEditable">
            <el-option
                v-for="rule in allroles"
                :key="rule.roleId"
                :label="`${rule.roleId}级策略：${rule.comment}`"
                :value="rule.roleId">
              <div class="option-content">
                <span class="rule-id">{{ rule.roleId }}</span>
                <span class="rule-comment">{{ rule.comment }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item v-if="isall" prop="comment" label="权限备注" :label-width="formLabelWidth">
          <el-input v-model="Adminform.comment" autocomplete="off" :readonly="true"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div v-if="isCreateMode === false">
          <el-button type="warning" @click="toggleEdit">编 辑</el-button>
          <el-button type="primary" @click="Editconfirm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div v-if="isCreateMode">
          <el-button type="primary" @click="confirmAdminAdd">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <!--策略新增或编辑页面-->
    <el-dialog v-bind:title="dialogTitle" :visible.sync="dialogRoleFormVisible">
      <el-form ref="Roleform" :rules="Rolerule" :model="Roleform" @submit.native.prevent>
        <el-form-item prop="rules" label="权限列表" :label-width="formLabelWidth">
          <el-select v-model="Roleform.rules" multiple placeholder="请选择权限">
            <el-option
                v-for="ruleId in allRules"
                :key="ruleId"
                :label="getLabelByRuleId(ruleId)"
                :value="ruleId">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 其他表单项 -->
      </el-form>
      <span slot="footer" class="dialog-footer">

        <!--新增-->
        <div v-if="!dialogRoleViewFormVisible">
            <el-button type="primary" @click="confirmAddRole">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
        <!--编辑-->
        <div v-if="dialogRoleViewFormVisible">
            <el-button type="primary" @click="confirmEditAdd">编 辑</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>

    </span>
    </el-dialog>

    <!--策略查看页面-->
    <el-dialog v-bind:title="dialogTitle" :visible.sync="dialogRoleViewFormVisible" >
      <el-table :data=this.allroles style="width: 100%">
        <el-table-column prop="roleId" label="策略ID" width="180"></el-table-column>
        <el-table-column prop="comment" label="详情"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="text" @click="handleRoleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleRoleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-footer style="text-align: center;">
      <el-pagination
          layout="total, prev, pager, next"
          :total="tableData.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange">
      </el-pagination>
    </el-footer>
  </el-container>
</template>
<script>
import http from '@/utils/http';
import {assertSourceType} from "@babel/core/lib/config/validation/option-assertions";
import {config} from "@vue/cli-plugin-eslint/eslintOptions";

export default {
  data() {
    return {
      loading: false,
      filteredList: [],
      Filter: '全部',
      search: "",
      currentPage: 1,
      pageSize: 10,
      allInfo: [],

      tableTitle: [
        { tableProp: "id", label: "管理员id" },
        { tableProp: "name", label: "管理员姓名" },
        { tableProp: "roleId", label: "策略id" },
  //      { tableProp: "rules", label: "权限列表" },
        { tableProp: "comment", label: "权限备注" }
      ],
      tableData: [],

      dialogRoleTitle: "新增策略",
      dialogAdminTitle: "新增管理员",
      dialogRoleViewTitle: "查看策略",
      dialogAdminFormVisible: false,
      dialogFormVisible: false,
      dialogRoleFormVisible: false,
      dialogRoleViewFormVisible: false,

      isCreateMode: false,
      isEditable: false,
      dialogTitle: '',
      formLabelWidth: '120px',
      originalForm: null,
      isall:false,

      Adminform: {
        id: '',
        name: '',
        password: '',
        newpassword: '',
        roleId: '',
        rules: [],
        comment: '',
        selectedRule: '', // 绑定下拉框选中的值
      },

      Roleform: {
        roleId:'',
        rules: [],
        comment: '',
      },

      allRules:[0,1,2,3,4,5],
      Rolerule: {
        rules: [
          { required: true, message: '权限列表不能为空', trigger: 'blur' }
        ],
      },

      rules: {
        name: [
          { required: true, message: '管理员姓名不能为空', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '策略ID不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
      },

      allroles: [],

      commentRules: [
        { id: 0, comment: '管理员' },
        { id: 1, comment: '人员' },
        { id: 2, comment: '房屋' },
        { id: 3, comment: '车辆' },
        { id: 4, comment: '车位' },
        { id: 5, comment: '门禁与传感器' },
      ],
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  mounted() {
    this.getAdminData();
  },
  methods: {
    cancel() {
      this.dialogRoleFormVisible = false;
      this.dialogAdminFormVisible = false;
      this.dialogRoleViewFormVisible = false;
      this.isEditable = false;
      this.isall = false;
    },
    getLabelByRuleId(ruleId){
      if( ruleId == '0' ) return '管理员管理权限';
      if( ruleId == '1' ) return '人员管理权限';
      if( ruleId == '2' ) return '房屋管理权限';
      if( ruleId == '3' ) return '车辆管理权限';
      if( ruleId == '4' ) return '车位管理权限';
      if( ruleId == '5' ) return '门禁与传感器管理权限';
    },
    handleRefresh() {
      this.getAdminData();
    },
    formatFlag(row,column,cellValue){
      return cellValue;
    },
    getAdminData() {
      this.loading = true;
      http.get("/admin/manage/getAllAdmin")
          .then((response) => {
            const Result = response.data;
            this.allInfo = Result.data;
            this.tableData = this.allInfo;
            this.loading = false;

            //写在请求里面，防止权限不足时跳转过来发送两条请求
            this.loading = true;
            http.get("/admin/manage/getAllRuleVo")
                .then((response) => {
                  const Result = response.data;
                  this.allroles = Result.data;
                  this.loading = false;
                }).catch(function (error) {
              console.error(error);
            });
          }).catch(function (error) {
        console.error(error);
      });
    },
    resetAdminForm() {
      this.$nextTick(() => {
        this.Adminform = {
          id: '',
          name: '',
          password: '',
          newpassword: '',
          roleId: '',
          rules: [],
          comment: '',
        };
        this.$refs.Adminform.resetFields();
      });
    },
    resetRoleForm() {
      this.$nextTick(() => {
        this.Roleform = {
          roleId: '',
          rules: [],
          comment: '',
        };
        this.$refs.Roleform.resetFields();
      });
    },
    handleAdd(commend) {
      if( commend == 'addAdmin' ){
          this.isall = false;
          this.dialogAdminFormVisible = true;
          this.isEditable = true;
          this.isCreateMode = true;
          this.dialogTitle = this.dialogAdminTitle;
          this.resetAdminForm();
      }
      if( commend == 'addRules' ){
          this.dialogRoleFormVisible = true;
          this.isEditable = true;
          this.isCreateMode = true;
          this.dialogTitle = this.dialogRoleTitle;
          this.resetRoleForm();
      }
      if( commend == 'viewRules') {
          this.dialogRoleViewFormVisible = true;
          this.dialogTitle = this.dialogRoleViewTitle;
      }
    },
    handleReset() {
      this.search = "";
      this.Filter = "全部";
      this.tableData = this.allInfo;
    },
    handleFilter(command) {
      this.Filter = command;
    },
    handleSearch() {
      if (this.search) {
        if (this.Filter === "全部") {
          this.tableData = this.allInfo.filter(item => {
            return Object.keys(item).some(key => {
              return this.tableTitle.some(title => title.tableProp === key) &&
                  item[key] && item[key].toString().toLowerCase().includes(this.search.toLowerCase());
            });
          });
        } else {
          const nowtable = this.tableTitle.find(item => item.label === this.Filter).tableProp;
          this.tableData = this.allInfo.filter(item => {
            const value = item[nowtable] ? item[nowtable].toString().toLowerCase() : '';
            return value.includes(this.search.toLowerCase());
          });
        }
      }
    },
    handleRoleEdit(row) {
      this.resetRoleForm();
      setTimeout(() => {
        this.Roleform = {...row};
        this.dialogTitle = '策略编辑';
        this.dialogRoleFormVisible = true;
      }, 100); // 2000 毫秒 = 2 秒
    },
    handleDetails(row) {
      this.resetAdminForm();
      setTimeout(() => {
          this.Adminform = {...row};
          this.originalForm = {...this.Adminform};
          this.isEditable = false;
          this.isCreateMode = false;
          this.dialogTitle = '管理员信息详情';
          this.isall = true;
          this.dialogAdminFormVisible = true;
      }, 100); // 2000 毫秒 = 2 秒
    },
    handleRoleDelete(row) {
      this.$confirm('此操作将永久删除条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.deleteRoleData(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.deleteData(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    deleteData(row) {
      this.tableData = this.tableData.filter(item => item != row);
      this.allInfo = this.tableData;

      const totalPages = Math.ceil(this.allInfo.length / this.pageSize);
      if (this.currentPage > totalPages) {
        this.currentPage -= 1;
      }
      http.get("/admin/manage/deleteAdmin", {
        params: {
          id: row.id
        }
      }).then(response => {
        console.log(response.data.data);
      })
    },
    deleteRoleData(row) {
      this.allroles = this.allroles.filter(item => item != row);
      http.get("/admin/manage/deleteRule", {
        params: {
          roleId: row.roleId
        }
      }).then(response => {
        console.log(response.data.data);
      })
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    toggleEdit() {
      this.$message.warning("正在进行编辑");
      this.isEditable = true;
    },
    updateComment(){
      //根据rules生成comment
      this.Roleform.comment = this.Roleform.rules.map(ruleId => {
        const rule = this.commentRules.find(r => r.id === ruleId);
        return rule ? rule.comment : `${ruleId}`;
      }).join('');
      this.Roleform.comment += '管理';
    },
    confirmAddRole(){
      this.$refs.Roleform.validate((valid) => {
        if (valid) {
          this.updateComment();
          http.post("/admin/manage/addRule", {
              rules: this.Roleform.rules,
              comment : this.Roleform.comment,
          })
              .then(response => {
                const Result = response.data;
                console.log(response);
                if (Result.success) {
                  this.getAdminData();
                  this.$message.success("添加成功！");
                  this.dialogRoleFormVisible = false;
                  this.isEditable = false;
                } else {
                  this.$message.error(Result.errorMsg);
                }
              })
              
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          return false;
        }
      });
      this.getAdminData();
      this.cancel();
    },
    confirmAdminAdd() {
      this.$refs.Adminform.validate((valid) => {
        if (valid) {
          http.get("/admin/manage/addAdmin", {
            params: {
                name: this.Adminform.name,
                password : this.Adminform.password,
                roleId: this.Adminform.roleId,
            }
          })
              .then(response => {
                const Result = response.data;
                console.log(response);
                if (Result.success) {
                  this.getAdminData();
                  this.$message.success("添加成功！");
                  this.dialogAdminFormVisible = false;
                  this.isEditable = false;
                } else {
                  this.$message.error(Result.errorMsg);
                }
              })
              .catch(error => {
                console.error(error);
                this.$message.error("请求失败！");
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          return false;
        }
      });
      this.cancel();
    },
    //编辑管理员确定
    Editconfirm() {
      this.$refs.Adminform.validate((valid) => {
        if (valid) {
          http.post('/admin/manage/updateAdmin', {
            id: this.Adminform.id,
            name: this.Adminform.name,
            password: this.Adminform.newpassword,
            role: this.Adminform.roleId,
          })
              .then(response => {
                const Result = response.data;
                if (Result.success) {
                  this.getAdminData();
                  this.$message.success("修改成功！");
                  this.dialogFormVisible = false;
                  this.isEditable = false;
                } else {
                  this.$message.error(Result.errorMsg);
                }
              })
              .catch(error => {
                console.error(error);
                this.$message.error("请求失败！");
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          this.Adminform = {...this.originalForm};
        }
      });
      this.cancel();
    },
    //策略编辑确定
    confirmEditAdd(){
      this.$refs.Roleform.validate((valid) => {
        if (valid) {
          this.updateComment();
          http.post('/admin/manage/updateRule', {
            roleId: this.Roleform.roleId,
            rules: this.Roleform.rules,
            comment: this.Roleform.comment,
          })
              .then(response => {
                const Result = response.data;
                if (Result.success) {
                  this.getAdminData();
                  this.$message.success("修改成功！");
                  this.dialogFormVisible = false;
                  this.isEditable = false;
                } else {
                  this.$message.error(Result.errorMsg);
                }
              })
              .catch(error => {
                console.error(error);
                this.$message.error("请求失败！");
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          this.Adminform = {...this.originalForm};
        }
      });
      this.cancel();
    },
  }
}
</script>

<style scoped lang="scss">
</style>